import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login", "/404"]; // no redirect whitelist   在没有登录的情况下这些页面是可以直接访问进入的

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  const hasToken = getToken(); //获取token

  if (hasToken) {
    //  表示已经登录过了
    if (to.path === "/login") {
      // if is logged in, redirect to the home page
      next({ path: "/" });
      NProgress.done();
    } else {
      //
      //if (!store.state.user.userInfo.userId) {
      if (!store.getters.userId) {
        const {
          roles: { menus }
        } = await store.dispatch("user/getUserInfo");
        //  获取动态路由   ...mapAction("user/getUserInfo")  ...mapAction("user",["getUserInfo"])
        //const result = await store.dispatch("permission", ["filterRoutes"]);
        const routes = await store.dispatch("permission/filterRoutes", menus);
        console.log(routes, 3334455);
        router.addRoutes([
          ...routes,
          { path: "*", redirect: "/404", hidden: true }
        ]); // 添加动态路由到路由表  铺路
        next(to.path);
      }
      //  有 token  但是 :去的是非登录页面
      next();
    }
  } else {
    //  表示未登陆,或者登陆token过期了
    /* has no token*/
    //  const whiteList = ["/login", "/404"];
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next(); //  "/login", "/404"
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`); //  输入 /  在  whiteList中没有   就直接回到登录页面中
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
